package cn.com.ghy.android.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.BaseKeyListener;
import android.text.method.NumberKeyListener;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import cn.com.ghy.android.exception.ProgramParseException;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:常用工具类
 * @author wuz  @date 2011-5-3 10:13:24
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class CommonUtil {
	public static InputFilter[] inputFilter = new InputFilter[] { new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
				int dstart, int dend) {
			return null;
		}
	}, new InputFilter.LengthFilter(16) };

	public static BaseKeyListener passwdListener = new NumberKeyListener() {
		public int getInputType() {
			return InputType.TYPE_MASK_VARIATION;
		}

		@Override
		protected char[] getAcceptedChars() {
			char[] keyChar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
					'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C',
					'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
					'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'0', '~', '_', '#', '$', '%', '^', '&'

			};
			return keyChar;
		}
	};

	public static BaseKeyListener charNumListener = new NumberKeyListener() {
		public int getInputType() {
			return InputType.TYPE_MASK_VARIATION;
		}

		@Override
		protected char[] getAcceptedChars() {
			char[] keyChar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
					'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C',
					'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
					'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'0', '+', '-', '*' };
			return keyChar;
		}
	};
	public static OnFocusChangeListener editTextToUpperCaseListener = //
	new OnFocusChangeListener() {
		public void onFocusChange(View v, boolean hasFocus) {
			if (v instanceof EditText) {
				EditText editText = (EditText) v;
				String str = editText.getText().toString().trim();
				if (!hasFocus && !"".equals(str)) {
					editText.setText(str.toUpperCase());
				}
			}
		}
	};
	public static TextWatcher decimalListener = new TextWatcher() {
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		public void afterTextChanged(Editable s) {
			String temp = s.toString();
			int posDot = temp.indexOf(".");
			if (posDot <= 0)
				return;
			if (temp.length() - posDot - 1 > 2) {
				s.delete(posDot + 3, posDot + 4);
			}
		}
	};

	public static byte[] decompressByteArray(byte abyte0[]) {
		Inflater inflater = new Inflater();
		inflater.setInput(abyte0);
		ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(abyte0.length);
		byte abyte1[] = new byte[1024];
		while (!inflater.finished())
			try {
				int i = inflater.inflate(abyte1);
				bytearrayoutputstream.write(abyte1, 0, i);
			} catch (DataFormatException dataformatexception) {
			}
		try {
			bytearrayoutputstream.close();
		} catch (IOException ioexception) {
		}
		return bytearrayoutputstream.toByteArray();
	}

	public static byte[] compressByteArray(byte abyte0[]) {
		Deflater deflater = new Deflater();
		deflater.setInput(abyte0);
		deflater.finish();
		ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(abyte0.length);
		byte abyte1[] = new byte[1024];
		while (!deflater.finished())
			try {
				int i = deflater.deflate(abyte1);
				bytearrayoutputstream.write(abyte1, 0, i);
			} catch (Exception e) {
			}
		try {
			bytearrayoutputstream.close();
		} catch (IOException ioexception) {
		}
		return bytearrayoutputstream.toByteArray();
	}

	public static String compressAndBase64ToString(String str) {
		if (str == null || "".equals(str)) {
			throw new RuntimeException("压缩加密的String不能为空或者空字符串!");
		}
		return org.kobjects.base64.Base64.encode(compressByteArray(str.getBytes()));
	}

	public static byte[] base64AndDecompressToByteArray(String str) {
		if (str == null) {
			return new byte[0];
		}

		byte[] buffer = org.kobjects.base64.Base64.decode(str);
		byte[] info = CommonUtil.decompressByteArray(buffer);

		return info;
	}

	public static TextWatcher txtTwoDecimalList = new TextWatcher() {

		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		public void afterTextChanged(Editable s) {
			String temp = s.toString();
			int posDot = temp.indexOf(".");
			if (posDot <= 0)
				return;
			if (temp.length() - posDot - 1 > 2) {
				s.delete(posDot + 3, posDot + 4);
			}
		}
	};

	@SuppressWarnings("rawtypes")
	public static void checkListNull(List list) throws Exception {
		if (null == list || list.size() == 0) {
			throw new ProgramParseException();
		}
	}

	@SuppressWarnings("rawtypes")
	public static void checkListNotNull(List list) throws Exception {
		if (null == list) {
			throw new ProgramParseException();
		}
	}

	public static String nextMonthId() {
		Calendar c = Calendar.getInstance();
		c.add(GregorianCalendar.MONTH, 1);
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		String monthid = "";

		if ((month + 1) < 10) {
			monthid = year + "0" + (month + 1);
		} else {
			monthid = year + "" + (month + 1);
		}
		return monthid;
	}

	public static String lastMonth(String monthid) {
		String lastMonth = "";
		Calendar cal = new GregorianCalendar();
		cal.set(Integer.parseInt(monthid.substring(0, 4)),
				Integer.parseInt(monthid.substring(4)) - 1, 1);
		cal.add(GregorianCalendar.MONTH, -1);
		String year = cal.get(GregorianCalendar.YEAR) + "";
		int month = (cal.get(GregorianCalendar.MONTH) + 1);

		if (month < 10) {
			lastMonth = year + "0" + month;
		} else {
			lastMonth = year + "" + month;
		}
		return lastMonth;
	}

	public static boolean isPhoneNumberValid(String phoneNumber) {
		boolean isValid = false;
		String expression = "^\\(?(\\d{3,4})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";

		String expression2 = "^\\(?(\\d{3,4})\\)?[- ]?(\\d{4})[- ]?(\\d{3,4})$";

		CharSequence inputStr = phoneNumber;
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);
		Pattern pattern2 = Pattern.compile(expression2);
		Matcher matcher2 = pattern2.matcher(inputStr);
		if (matcher.matches() || matcher2.matches()) {
			isValid = true;
		}
		return isValid;
	}

	public static String formateDate(int year, int monthOfYear, int dayOfMonth) {
		String monthStr = "";
		String dayStr = "";

		if (monthOfYear + 1 < 10) {
			monthStr = "0" + (monthOfYear + 1);
		} else {
			monthStr = (monthOfYear + 1) + "";
		}

		if (dayOfMonth < 10) {
			dayStr = "0" + dayOfMonth;
		} else {
			dayStr = dayOfMonth + "";
		}
		return year + "-" + monthStr + "-" + dayStr;
	}

	public static boolean checkDate(Context context, String startDateStr, String endDateStr) {
		boolean flag = true;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = format.parse(startDateStr);
			endDate = format.parse(endDateStr);
		} catch (ParseException e) {
			throw new RuntimeException("检测查询时间格式化错误！");
		}
		int result = startDate.compareTo(endDate);
		if (result == 1) {
			Toast.makeText(context, "开始日期必须小于结束日期!", Toast.LENGTH_SHORT).show();
			flag = false;
		} else if (result == 0) {
			Toast.makeText(context, "开始日期不能等于结束日期!", Toast.LENGTH_SHORT).show();
			flag = false;
		}
		return flag;
	}
}
